<!--
 * @description:
 * @author: cuicui
 * @Date: 2023-11-28 19:51:46
 * @LastEditTime: 2023-11-30 11:47:52
 * @LastEditors: cuicui
-->
<template>
  <a-modal
    :title='currentTitle'
    :width='740'
    :visible='visible'
    :confirmLoading='loading'
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
    v-bind='edit ? {} : {footer: null}'
  >
    <div style='max-height: 500px;overflow: auto'>
      <a-spin :spinning='loading'>
        <a-tabs v-model='activeKey'>
          <a-tab-pane key='0' tab='缺陷详情'>
            <a-form :form='form' v-bind='formLayout'>
              <a-form-item label='主键' v-show='false'>
                <a-input :disabled='!edit' v-decorator="['id']" />
              </a-form-item>

              <a-form-item label='缺陷等级'>
                <a-select placeholder='请选择缺陷等级'
                          :disabled='!edit'
                          :options='defectLevelDicList'
                          v-decorator="['defectLevelDicId', {rules:[{  required: true, message: '请选择缺陷等级!' }]}]">
                </a-select>
              </a-form-item>

              <a-form-item label='站点'>
                <a-select placeholder='请选择站点'
                          :disabled='!edit'
                          :options='stationList'
                          v-decorator="['stationDicId', {rules:[{  required: true, message: '请选择站点!' }]}]">
                </a-select>
              </a-form-item>

              <a-form-item label='设备'>
                <a-select placeholder='请选择设备'
                          :disabled='!edit'
                          :options='deviceList'
                          v-decorator="['deviceId', {rules:[{  required: true, message: '请选择设备!' }]}]">
                </a-select>
              </a-form-item>

              <a-form-item label='缺陷描述'>
                <a-textarea placeholder='请输入缺陷描述'
                            :disabled='!edit'
                            v-decorator="['desc',{ rules: [ {  required: true, message: '请输入缺陷描述!' }] }]" />
              </a-form-item>

              <a-form-item label='期望完成时间'>
                <a-date-picker :disabled='!edit' style='width: 100%;' placeholder='请选择期望完成时间'
                               v-decorator="['expectedCompletionTime']" valueFormat='YYYY-MM-DD' />
              </a-form-item>

              <a-form-item label='缺陷图片'>
                <a-upload
                  name='file'
                  :disabled='!edit'
                  list-type='picture-card'
                  class='avatar-uploader'
                  :show-upload-list='false'
                  v-decorator="['defectPhotoPath',
            {
              valuePropName: 'defectPhotoPath',
              getValueFromEvent: normFile,
            }]"
                  :action='uploadPath'
                  :headers='computedHeaders'
                  :before-upload='beforeUpload'
                  @change='handleChange'
                >
                  <img class='avatar' v-if='imageUrl' :src='imageUrl' alt='avatar' />
                  <div v-else>
                    <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
                    <div class='ant-upload-text'>
                      上传缺陷图片
                    </div>
                  </div>
                </a-upload>
              </a-form-item>

              <a-form-item label='指派备注' v-if='model && model.status !== "1"'>
                <div class='view-item' style='height: 100px;'>
                  <p>
                    {{ model.desc }}
                  </p>
                </div>
              </a-form-item>

              <a-form-item label='归档备注'  v-if='model && model.status === "3"'>
                <div class='view-item' style='height: 100px;'>
                  <p>
                    {{ model.archiveMessage }}
                  </p>
                </div>
              </a-form-item>
            </a-form>
          </a-tab-pane>
          <a-tab-pane key='1' tab='流转情况' :disabled='!!(!model || !model.id)'>
            <a-timeline>
              <a-timeline-item color='green' v-for='item in defectManagementLogList' :key='item.id'>
                {{ moment(item.operationTime).format('YYYY-MM-DD HH:mm:ss') }}：{{ item.operator + item.operation }}
              </a-timeline-item>
            </a-timeline>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </div>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { findDataDicInfoByType } from '@/api/dataDicInfo'
import { findBypageEquipment } from '@/api/equipmentManagement'
import api, { downloadAvatar } from '@/api/workerOrder'
import { getDefectDetail } from '@/api/defectManagement'
import TagSelectOption from '@/components/TagSelect/TagSelectOption'
import { mapState } from 'vuex'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import moment from 'moment'
// 表单字段
const fields = ['id', 'defectLevelDicId', 'expectedCompletionTime', 'defectPhotoPath', 'desc', 'deviceId', 'stationDicId']
let baseUrl = window.PROJECT_CONFIG.VUE_APP_API_BASE_URL
export default {
  components: { TagSelectOption },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    edit: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    moment() {
      return moment
    },
    ...mapState({
      token: state => state.user.token
    }),
    computedHeaders() {
      return {
        [ACCESS_TOKEN]: `Bearer ${this.token}`
      }
    },
    currentTitle() {
      let title = ''
      if (this.edit && (!this.model || !this.model.id)) {
        title = '新增缺陷'
      }
      if (this.edit && this.model && this.model.id) {
        title = '编辑缺陷'
      }
      if (!this.edit) {
        title = '缺陷详情'
      }
      return title
    }
  },
  data() {
    this.baseUrl = baseUrl
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      }
    }
    return {
      form: this.$form.createForm(this),
      queryParam: {},
      defectLevelDicList: [],
      uploadPath: baseUrl + api.uploadWorkOrderPhoto,
      defectManagementLogList: [],
      stationList: [],
      deviceList: [],
      systemId: '',
      imageUrl: '',
      activeKey: '0',
      uploadLoading: false
    }
  },
  created() {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    this.getLeavelDic()
    this.getStationList()
    this.getDeviceList()
    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.getDefectDetail()
      this.model && this.form.setFieldsValue(pick(this.model, fields))
      console.log(this.model, 'this.modelthis.modelthis.modelthis.model')
      if (this.form.getFieldValue('defectPhotoPath')) {
        const defectPhotoPath = this.form.getFieldValue('defectPhotoPath')
        this.imageUrl = downloadAvatar({ fileName: defectPhotoPath })
      } else {
        this.imageUrl = ''
      }
    })
  },
  methods: {
    getDefectDetail() {
      if (!this.model || !this.model.id) {
        return
      }
      getDefectDetail({
        defectId: this.model.id
      }).then(res => {
        this.defectManagementLogList = res.defectManagementLogList
      })
    },
    getLeavelDic() {
      findDataDicInfoByType(14).then(res => {
        this.defectLevelDicList = res.map(item => {
          return {
            ...item,
            key: Number(item.code),
            label: item.name
          }
        })
      })
    },
    getStationList() {
      findDataDicInfoByType(0).then(res => {
        this.stationList = res.map(item => {
          return {
            ...item,
            key: Number(item.id),
            label: item.name
          }
        })
      })
    },
    getDeviceList() {
      findBypageEquipment({ pageNum: 1, pageSize: 999 }).then(res => {
        this.deviceList = res.list.map(item => {
          return {
            ...item,
            label: item.equipmentName,
            key: Number(item.id)
          }
        })
      })
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.imageUrl = downloadAvatar({ fileName: info.file.response.result })
        this.uploadLoading = false
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/JEPG'
      if (!isJpgOrPng) {
        this.$message.error('仅支持JPEG格式以及PNG格式文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('图片大小不得超过 10MB!')
      }
      return isJpgOrPng && isLt2M
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e
      }
      if (e.fileList && e.fileList.length) {
        return e && e.fileList[0].response && e.fileList[0].response.result
      }
      return ''
    }
  }
}
</script>
<style lang='less' scoped>
.ant-modal-body {
  height: 700px;
  overflow: auto;
}

.avatar {
  width: 200px;
  height: 200px;
}
</style>
